package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cloudbroker.bcs.common.constants.type.BusinessType;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.credits.api.vo.back.CreditsVO;
import com.cloudbroker.bcs.csvc.credits.api.vo.request.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.CreditsBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.CreditsLimitAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.CreditsLimitQueryForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.CreditsLimitUpdateForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.QueryCreditsForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.QueryCreditslogForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.TaskProgressQueryForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.CreditsRuleAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.credits.vo.UserCreditsForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.credits.*;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.credits.CreditsExtService;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.CreditsCacheUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lili19289 on 2016/11/22.
 */
@Service
public class CreditsBizServiceImpl implements CreditsBizService {

    @Resource
    private CreditsRuleService creditsRuleService;
    @Resource
    private TaskConfigureService taskConfigureService;
    @Resource
    private TaskProgressService taskProgressService;

    @Resource
    private CreditsLimitService creditsLimitService;

    @Resource
    private CreditsExtService creditsExtService;

    @Resource
    private CreditsLogService creditsLogService;

    @Override
    public CreditsBackVO function_get_user_credits(UserCreditsForm form){
        com.cloudbroker.bcs.csvc.credits.api.vo.request.UserCreditsForm creditsForm = new  com.cloudbroker.bcs.csvc.credits.api.vo.request.UserCreditsForm();
        creditsForm.setUser_id(form.getUser().getUser_id());
        creditsForm.setCompany_id(form.getUser().getCompany_id());
        CreditsVO creditsVO=creditsExtService.functionGetCreditsByUser(creditsForm);
        CreditsBackVO creditsBackVO = new CreditsBackVO();
        creditsBackVO.setUser_id(creditsVO.getUser_id());
        creditsBackVO.setTotal_credits(creditsVO.getHistory_credits());
        creditsBackVO.setUser_credits(creditsVO.getUser_credits());
        creditsBackVO.setCost_credits(creditsVO.getCost_credits());
        creditsBackVO.setCurrent_credits(CreditsCacheUtil.getTotalCache(form.getUser().getUser_id(),form.getUser().getCompany_id()));
        //查看昨天完成任务的奖励情况
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("user_id",form.getUser().getUser_id());
        paramMap.put("company_id",form.getCompany_id());
        paramMap.put("start_time",CreditsCacheUtil.getStartTime()-24*60*60000);
        paramMap.put("end_time",CreditsCacheUtil.getEndTime()-24*60*60000);
        Integer maxMultiply = taskProgressService.findMaxMultiply(paramMap);
        if(maxMultiply !=null){
            creditsBackVO.setMultiply(maxMultiply);
        }else{
            creditsBackVO.setMultiply(1);
            maxMultiply=1;
        }
        int creditsLimitValue = CreditsCacheUtil.getLimitCache(form.getCompany_id());
        if(creditsLimitValue==0){
            CreditsLimit creditsLimit = creditsLimitService.findByCompany(form.getCompany_id());
            if(creditsLimit !=null) {
                CreditsCacheUtil.addLimitCache(form.getCompany_id(), creditsLimit.getCredits_limit_value());
                creditsLimitValue = creditsLimit.getCredits_limit_value();
            }
        }
        creditsBackVO.setLimit_credits(creditsLimitValue*maxMultiply);
        return VOUtil.setSuccessResult(creditsBackVO);
    }


    @Override
    public CreditsLogListBackVO function_query_creditsLog(QueryCreditslogForm form){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("start_time",form.getStart_time());
        paramMap.put("end_time",form.getStart_time());
        paramMap.put("user_id",form.getUser().getUser_id());
        paramMap.put("company_id",form.getCompany_id());
        paramMap.put("start_index",(form.getPage_no()-1)*form.getRequest_num());
        paramMap.put("end_index",form.getRequest_num());
        List<CreditsLog> creditsLogs = creditsLogService.queryLogs(paramMap);
        List<CreditsLogBackVO> list = JSON.parseObject(JSON.toJSONString(creditsLogs),new TypeReference<List<CreditsLogBackVO>>(){});
        CreditsLogListBackVO vo= new CreditsLogListBackVO();
        vo.setData_list(list);
        return VOUtil.setSuccessResult(vo);
    }


    public TaskProgressListBackVO  function_query_task_progress(TaskProgressQueryForm form){
        long user_id = form.getUser().getUser_id();
        String company_id = form.getUser().getCompany_id();
        TaskConfigure taskConfigureParam = new TaskConfigure();
        taskConfigureParam.setCompany_id(company_id);
        List<TaskConfigure> taskConfigures = taskConfigureService.query(taskConfigureParam);
        TaskProgress taskProgressParam = new TaskProgress();
        taskProgressParam.setCompany_id(company_id);
        taskProgressParam.setUser_id(user_id);
        List<TaskProgress> finishTaskProgresses = taskProgressService.query(taskProgressParam);
        List<TaskProgressBackVO> taskProgressBackVOs = new ArrayList<>();
        Map<Long,TaskProgress> taskProgressMap = new HashMap<>();
        for(TaskProgress taskProgress : finishTaskProgresses){
            taskProgressMap.put(taskProgress.getTask_id(),taskProgress);
        }
        for(TaskConfigure taskConfigure : taskConfigures){
            TaskProgress currentProgress = taskProgressMap.get(taskConfigure.getTask_id());
            //任务未完成
            if(currentProgress==null){
                currentProgress = CreditsCacheUtil.getTaskProgress(user_id,company_id,taskConfigure.getTask_id());
            }
            //任务未开始
            if(currentProgress==null){
                currentProgress= new TaskProgress();
                currentProgress.setTask_id(taskConfigure.getTask_id());
                currentProgress.setCompany_id(company_id);
                currentProgress.setUser_id(user_id);
                currentProgress.setCompleted_count(0);
                currentProgress.setTarget_count(taskConfigure.getTask_count());
                currentProgress.setBusiness_type( taskConfigure.getBusiness_type());
            }
            currentProgress.setMemo(taskConfigure.getMemo());
            TaskProgressBackVO taskProgressBackVO = JSON.parseObject(JSON.toJSONString(currentProgress),TaskProgressBackVO.class);
            taskProgressBackVO.setNext_task_id(taskConfigure.getUpgrade_id());
            taskProgressBackVO.setMemo(taskConfigure.getMemo());
            taskProgressBackVO.setTask_status(taskProgressBackVO.getTarget_count()-taskProgressBackVO.getCompleted_count());
            taskProgressBackVO.setTask_award(taskConfigure.getTask_award());
            taskProgressBackVO.setTask_level(taskConfigure.getTask_level());
            BusinessType type=BusinessType.convertEnum(taskProgressBackVO.getBusiness_type());
            taskProgressBackVO.setTitle(type.toTitle());
            taskProgressBackVOs.add(taskProgressBackVO);

        }

        TaskProgressListBackVO listBackVO = new TaskProgressListBackVO();
        listBackVO.setData_list(taskProgressBackVOs);
        return VOUtil.setSuccessResult(listBackVO);
    }


    @Override
    public ResultVO func_add_credits_rule(CreditsRuleAddForm form) {
        CreditsRule creditsRule = JSON.parseObject(JSON.toJSONString(form),CreditsRule.class);
        CreditsRule existRule = creditsRuleService.findByBusinessType(creditsRule);
        if(existRule != null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CreditsErrorInfo.CREDIT_RULE_EXIST,ResultVO.class);
        }
        creditsRuleService.save(creditsRule);
        return ResultVO.success(creditsRule.getCredits_rule_id());
    }

    @Override
    public HSBCPSBackVO func_update_credits_rule(CreditsRuleUpdateform form) {
        CreditsRule creditsRule = JSON.parseObject(JSON.toJSONString(form),CreditsRule.class);
        creditsRuleService.update(creditsRule);
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public HSBCPSBackVO func_delete_credits_rule(CreditsRuleDeleteForm form) {
        CreditsRule creditsRule = JSON.parseObject(JSON.toJSONString(form),CreditsRule.class);
        creditsRuleService.deleteByEntity(creditsRule);
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public CreditsRuleListBackVO func_query_credits_rule(QueryCreditsRuleForm form) {
        CreditsRule creditsRule = JSON.parseObject(JSON.toJSONString(form),CreditsRule.class);
        Pagination page = new Pagination();
        page.setStart_index(form.getStart_row());
        page.setPage_size(form.getRequest_num());
        creditsRule.setPage(page);
        List<CreditsRule> creditsRules = creditsRuleService.query(creditsRule);
        List<CreditsRuleBackVO> creditsRuleBackVOs = JSON.parseObject(JSON.toJSONString(creditsRules),new TypeReference<List<CreditsRuleBackVO>>(){});
        CreditsRuleListBackVO creditsRuleListBackVO = new CreditsRuleListBackVO();
        creditsRuleListBackVO.setData_list(creditsRuleBackVOs);
        return  VOUtil.setSuccessResult(creditsRuleListBackVO);
    }

    @Override
    public ResultVO funct_add_tasck_configure(TaskAddForm form) {
        TaskConfigure taskConfigure = JSON.parseObject(JSON.toJSONString(form),TaskConfigure.class);
        TaskConfigure existTask = taskConfigureService.findByBusinessType(taskConfigure.getBusiness_type(),taskConfigure.getTask_level(),taskConfigure.getCompany_id());
        if(existTask!=null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CreditsErrorInfo.CREDIT_TASk_EXIST,ResultVO.class);
        }
        taskConfigureService.save(taskConfigure);
        return ResultVO.success(taskConfigure.getTask_id());
    }

    @Override
    public HSBCPSBackVO func_update_task_configure(TaskUpdateForm form) {
        TaskConfigure taskConfigure = JSON.parseObject(JSON.toJSONString(form),TaskConfigure.class);
        taskConfigureService.update(taskConfigure);
        return VOUtil.genSuccessBackVo();

    }

    @Override
    public HSBCPSBackVO func_delete_task_configure(TaskDeleteForm form) {
        TaskConfigure taskConfigure = JSON.parseObject(JSON.toJSONString(form),TaskConfigure.class);
        taskConfigureService.deleteByEntity(taskConfigure);
        return VOUtil.genSuccessBackVo();
    }

    @Override
    public TaskConfigureListBackVO func_query_task_configure(TaskQueryForm form) {
        TaskConfigure taskConfigure = JSON.parseObject(JSON.toJSONString(form),TaskConfigure.class);
        Pagination page = new Pagination();
        page.setStart_index(form.getStart_row());
        page.setPage_size(form.getRequest_num());
        taskConfigure.setPage(page);
        List<TaskConfigure> taskConfigures = taskConfigureService.query(taskConfigure);
        List<TaskConfigureBackVO> backVOs = JSON.parseObject(JSON.toJSONString(taskConfigures),new TypeReference<List<TaskConfigureBackVO>>(){});
        TaskConfigureListBackVO listBackVO = new TaskConfigureListBackVO();
        listBackVO.setData_list(backVOs);
        return  VOUtil.setSuccessResult(listBackVO);
    }



    public ResultVO func_add_credlits_limit(CreditsLimitAddForm form){
        CreditsLimit creditsLimit = JSON.parseObject(JSON.toJSONString(form),CreditsLimit.class);
        CreditsLimit limit = creditsLimitService.findByCompany(form.getCompany_id());
        if(limit!=null){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.CreditsErrorInfo.CREDIT_LIMIT_EXIST,ResultVO.class);
        }
        creditsLimitService.save(creditsLimit);
        CreditsLimitBackVO creditsLimitBackVO = new CreditsLimitBackVO();
        creditsLimitBackVO.setCredits_limit_id(creditsLimit.getCredits_limit_id());
        return ResultVO.success(creditsLimit.getCredits_limit_id());
    }

    public HSBCPSBackVO func_update_credlits_limit(CreditsLimitUpdateForm form){
        CreditsLimit creditsLimit = JSON.parseObject(JSON.toJSONString(form),CreditsLimit.class);
        creditsLimitService.update(creditsLimit);
        CreditsCacheUtil.addLimitCache(creditsLimit.getCompany_id(), creditsLimit.getCredits_limit_value());
        return VOUtil.genSuccessBackVo();
    }

    public HSBCPSBackVO func_delete_credlits_limit(CreditsLimitDeleteForm  form){
        creditsLimitService.delete(form.getCredits_limit_id());
        return VOUtil.genSuccessBackVo();
    }

    public CreditsLimitListBackVO func_query_credits_limit(CreditsLimitQueryForm form){
        CreditsLimit creditsLimit = JSON.parseObject(JSON.toJSONString(form),CreditsLimit.class);
        Pagination pagination = new Pagination();
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        creditsLimit.setPage(pagination);
        List<CreditsLimit> creditsLimits =creditsLimitService.query(creditsLimit);
        List<CreditsLimitBackVO> backVOList = JSON.parseObject(JSON.toJSONString(creditsLimits),new TypeReference<List<CreditsLimitBackVO>>(){});
        CreditsLimitListBackVO listBackVO = new CreditsLimitListBackVO();
        listBackVO.setData_list(backVOList);
        return  VOUtil.setSuccessResult(listBackVO);

    }


}
